package com.hunttown.mes.common.utils;


import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Properties;

/**
 * 注释：引入FreeMarker  获取freeMarker内容
 * created by hunttown on 2017/9/3
 */
public class VelocityUtils {

    private VelocityUtils() {
    }

    private static String cfg = "/velocity.properties";

    static {
        try {
            Properties properties = new Properties();
            properties.load(VelocityUtils.class.getClassLoader().getResourceAsStream(cfg));
            Velocity.init(properties);
            System.out.println("Velocity工具类初始化完成！");

        } catch (Exception e) {
            System.out.println("Velocity工具类加载失败！");
            e.printStackTrace();
        }
    }

    /**
     * 注释：根据模板名称 、模板值输入模板内容
     */
    public static String getTemplateContent(String templatePahe, VelocityContext context) {
        String builder = "";

        //获取模板
        try {
            Template template = Velocity.getTemplate(templatePahe, "UTF-8");
            if (template == null) {
                return null;
            }

            //获取输出流 - 将template 内容输出到stringBuilder
            StringWriter stringWriter = new StringWriter();
            template.merge(context, stringWriter);

            builder = stringWriter.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder;
    }

    public static void main(String[] args) {
        VelocityContext context = new VelocityContext();
        context.put("name", "abc");
        getTemplateContent("", context);
    }

}
